package com.datastructure.test.exangestock;

public class ExchangeStock {

    int max = 0;
    int initial = 0;
    public static void main(String[] args) {

    }

    public int maxProfit (int[] prices) {
        // write code here
        for (int i = 0; i < prices.length; i++) {
            initial = prices[i];
            for(int j = i+1;j<prices.length;j++){
                if(prices[j]==initial){
                    continue;
                }
                if(j>i+1&&prices[j]==prices[j-1]){
                    continue;
                }
                if(prices[j]>initial){
                    max = Math.max(max,prices[j]-initial);
                }
            }
        }
        return max;
    }

    public int maxProfit1 (int[] prices) {
        // write code here
        int len = prices.length;
        int minPrices = Integer.MAX_VALUE;
        int ans = 0;
        for(int i=0;i<len;i++){
            //寻找最低点
            if(prices[i]<minPrices){
                minPrices = prices[i];
            }else if(prices[i]-minPrices>ans){
                //更新答案（最大利润）
                ans = prices[i]-minPrices;
            }
        }
        return ans;
    }

    public int maxProfit2 (int[] prices) {
        // write code here
        if (prices == null || prices.length < 2)
            return 0;
        int total = 0, index = 0, length = prices.length;
        while (index < length-1) {
            //如果股票下跌就一直找，直到找到股票开始上涨为止
            while (index < length - 1 && prices[index] >= prices[index + 1])
                index++;
            //股票上涨开始的值，也就是这段时间上涨的最小值
            int min = prices[index];
            //一直找到股票上涨的最大值为止
            while (index < length - 1 && prices[index] <= prices[index + 1])
                index++;
            //计算这段上涨时间的差值，然后累加
            total += prices[index++] - min;
        }
        return total;
    }
}
